using BXS.API.Models;
using Microsoft.AspNetCore.Mvc;

namespace BXS.API.Controllers
{
    /// <summary>
    /// AI咨询管理控制器
    /// </summary>
    public class AiInquiriesController : BaseController
    {
        // 模拟数据
        private static List<AiInquiry> _aiInquiries = new List<AiInquiry>
        {
            new AiInquiry 
            { 
                Id = 1, 
                InquiryNo = "AI20240101001", 
                CustomerName = "张三", 
                CustomerPhone = "13800138001", 
                TotalAmount = 3898, 
                Status = "pending", 
                CreateTime = "2024-01-01",
                Products = new List<AiInquiryProduct>
                {
                    new AiInquiryProduct { Name = "玉石骨灰盒", Quantity = 1, EstimatedPrice = 2999 },
                    new AiInquiryProduct { Name = "白菊花束", Quantity = 3, EstimatedPrice = 299 }
                },
                AiResponse = "根据图片识别，包含玉石骨灰盒1个，白菊花束3束，预估总价3898元。",
                AdminResponse = null
            },
            new AiInquiry 
            { 
                Id = 2, 
                InquiryNo = "AI20240102001", 
                CustomerName = "李四", 
                CustomerPhone = "13800138002", 
                TotalAmount = 899, 
                Status = "replied", 
                CreateTime = "2024-01-02",
                Products = new List<AiInquiryProduct>
                {
                    new AiInquiryProduct { Name = "寿衣套装", Quantity = 1, EstimatedPrice = 899 }
                },
                AiResponse = "识别到寿衣套装1套，预估价格899元。",
                AdminResponse = "您好，寿衣套装价格准确，如需购买请联系客服。"
            },
            new AiInquiry 
            { 
                Id = 3, 
                InquiryNo = "AI20240103001", 
                CustomerName = "王五", 
                CustomerPhone = "13800138003", 
                TotalAmount = 598, 
                Status = "processing", 
                CreateTime = "2024-01-03",
                Products = new List<AiInquiryProduct>
                {
                    new AiInquiryProduct { Name = "白菊花束", Quantity = 2, EstimatedPrice = 299 }
                },
                AiResponse = "识别到白菊花束2束，预估价格598元。",
                AdminResponse = null
            },
        };

        /// <summary>
        /// 获取AI咨询列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="status">状态筛选</param>
        /// <returns>AI咨询列表</returns>
        [HttpGet]
        public ActionResult<PagedApiResponse<AiInquiry>> GetAiInquiries([FromQuery] int page = 1, [FromQuery] int pageSize = 10, [FromQuery] string? status = null)
        {
            var query = _aiInquiries.AsQueryable();
            
            if (!string.IsNullOrEmpty(status) && status != "all")
            {
                query = query.Where(a => a.Status == status);
            }

            var total = query.Count();
            var skip = (page - 1) * pageSize;
            var aiInquiries = query.OrderByDescending(a => a.CreateTime).Skip(skip).Take(pageSize).ToList();
            
            return PagedSuccess(aiInquiries, total, page, pageSize);
        }

        /// <summary>
        /// 根据ID获取AI咨询
        /// </summary>
        /// <param name="id">AI咨询ID</param>
        /// <returns>AI咨询信息</returns>
        [HttpGet("{id}")]
        public ActionResult<ApiResponse<AiInquiry>> GetAiInquiry(int id)
        {
            var aiInquiry = _aiInquiries.FirstOrDefault(a => a.Id == id);
            if (aiInquiry == null)
            {
                return Error<AiInquiry>("AI咨询不存在", 404);
            }
            return Success(aiInquiry);
        }

        /// <summary>
        /// 创建AI咨询
        /// </summary>
        /// <param name="request">创建AI咨询请求</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public ActionResult<ApiResponse<AiInquiry>> CreateAiInquiry([FromBody] CreateAiInquiryRequest request)
        {
            if (string.IsNullOrEmpty(request.CustomerName) || string.IsNullOrEmpty(request.CustomerPhone) || !request.Products.Any())
            {
                return Error<AiInquiry>("请填写完整信息");
            }

            var totalAmount = request.Products.Sum(p => p.EstimatedPrice * p.Quantity);
            var inquiryNo = $"AI{DateTime.Now:yyyyMMdd}{_aiInquiries.Count + 1:D3}";

            // 模拟AI识别结果
            var aiResponse = $"根据图片识别，包含{string.Join("、", request.Products.Select(p => $"{p.Name}{p.Quantity}个"))}，预估总价{totalAmount}元。";

            var newAiInquiry = new AiInquiry
            {
                Id = _aiInquiries.Count > 0 ? _aiInquiries.Max(a => a.Id) + 1 : 1,
                InquiryNo = inquiryNo,
                CustomerName = request.CustomerName,
                CustomerPhone = request.CustomerPhone,
                TotalAmount = totalAmount,
                Status = "pending",
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                Products = request.Products,
                AiResponse = aiResponse,
                AdminResponse = null
            };

            _aiInquiries.Add(newAiInquiry);
            return Success(newAiInquiry, "AI咨询创建成功");
        }

        /// <summary>
        /// 更新AI咨询状态
        /// </summary>
        /// <param name="id">AI咨询ID</param>
        /// <param name="request">状态更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}/status")]
        public ActionResult<ApiResponse<AiInquiry>> UpdateAiInquiryStatus(int id, [FromBody] UpdateAiInquiryStatusRequest request)
        {
            var aiInquiry = _aiInquiries.FirstOrDefault(a => a.Id == id);
            if (aiInquiry == null)
            {
                return Error<AiInquiry>("AI咨询不存在", 404);
            }

            if (string.IsNullOrEmpty(request.Status))
            {
                return Error<AiInquiry>("状态不能为空");
            }

            aiInquiry.Status = request.Status;
            return Success(aiInquiry, "AI咨询状态更新成功");
        }

        /// <summary>
        /// 回复AI咨询
        /// </summary>
        /// <param name="id">AI咨询ID</param>
        /// <param name="request">回复请求</param>
        /// <returns>回复结果</returns>
        [HttpPut("{id}/reply")]
        public ActionResult<ApiResponse<AiInquiry>> ReplyAiInquiry(int id, [FromBody] ReplyAiInquiryRequest request)
        {
            var aiInquiry = _aiInquiries.FirstOrDefault(a => a.Id == id);
            if (aiInquiry == null)
            {
                return Error<AiInquiry>("AI咨询不存在", 404);
            }

            if (string.IsNullOrEmpty(request.Response))
            {
                return Error<AiInquiry>("回复内容不能为空");
            }

            aiInquiry.AdminResponse = request.Response;
            aiInquiry.Status = "replied";
            return Success(aiInquiry, "AI咨询回复成功");
        }

        /// <summary>
        /// 删除AI咨询
        /// </summary>
        /// <param name="id">AI咨询ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public ActionResult<ApiResponse<bool>> DeleteAiInquiry(int id)
        {
            var aiInquiry = _aiInquiries.FirstOrDefault(a => a.Id == id);
            if (aiInquiry == null)
            {
                return Error<bool>("AI咨询不存在", 404);
            }

            _aiInquiries.Remove(aiInquiry);
            return Success(true, "AI咨询删除成功");
        }

        /// <summary>
        /// 获取AI咨询状态列表
        /// </summary>
        /// <returns>状态列表</returns>
        [HttpGet("statuses")]
        public ActionResult<ApiResponse<List<string>>> GetStatuses()
        {
            var statuses = _aiInquiries.Select(a => a.Status).Distinct().ToList();
            return Success(statuses);
        }
    }
} 